package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.config.constant.WorkflowConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.CompareUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.explain.FormDataDetailFormExplainHandleName;
import com.xbongbong.parent.parse.data.FormDataDetailAnalysisDataHelp;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.label.pojo.LabelForDetailUpadatePojo;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.enums.BirthdayTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.UserTeamEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.util.DepartmentFieldUtil;
import com.xbongbong.saas.util.UserFieldUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowDataChangeRecordEntity;
import com.xbongbong.workflow.model.WorkflowDataChangeRecordModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.pojo.changerecord.ChangeRecordMidPojo;
import com.xbongbong.workflow.pojo.changerecord.ChangeRecordOtherFieldBasicPojo;
import com.xbongbong.workflow.pojo.changerecord.ChangeRecordSubFormColumnPojo;
import com.xbongbong.workflow.pojo.changerecord.ChangeRecordSubFormFieldBasicPojo;
import com.xbongbong.workflow.pojo.changerecord.ValuePojo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: 汪腾伟
 * @date: Created in 2022/9/23 15:22
 * @description： 工作流这边编辑进审批场景下需要记录每次变更日志的帮助类。一些工具类方法抽取到这边，
 *                避免工作流核心类{@link com.xbongbong.paas.service.impl.WorkflowApprovalOperateImpl}非核心逻辑太多
 */
@Slf4j
@Component
public class WorkflowRecordLogHelp {

    @Resource
    private FormDataDetailAnalysisDataHelp formDataDetailAnalysisDataHelp;
    @Resource
    private FormDataDetailFormExplainHandleName formDataDetailFormExplainHandleName;
    @Resource
    private OwnerAndCoUserHelp ownerAndCoUserHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private WorkflowDataChangeRecordModel workflowDataChangeRecordModel;
    @Resource
    private FormDataHelp formDataHelp;

    /**
     * 记录工作流数据在审批中的变动，以记录的形式存储到tb_workflow_data_change_record表中
     */
    @Async(value = "addUpdateDelThreadPool")
    public void recordDataChange(ChangeRecordMidPojo changeRecordMidPojo) throws XbbException {
        if (Objects.nonNull(changeRecordMidPojo)) {
            //代表是编辑进审批的，新建进审批的不会去查询这个值
            Long formId = changeRecordMidPojo.getFormId();
            String corpid = changeRecordMidPojo.getCorpid();
            Integer businessType = changeRecordMidPojo.getBusinessType();
            Long dataId = changeRecordMidPojo.getDataId();
            Integer saasMark = changeRecordMidPojo.getSaasMark();
            UserVO userVO = changeRecordMidPojo.getUserVO();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>();
            if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
                explainMap = ExplainUtil.getExplainMap(workOrderExplainEntityExt.getExplains(), null);
            }else {
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
            }
            //主要是为了循环字段，进行值比较使用
            JSONObject originalOldData = changeRecordMidPojo.getOriginalOldData();
            JSONObject originalNewData = changeRecordMidPojo.getOriginalNewData();
            JSONObject oldData = (JSONObject) CloneUtil.deepClone(originalOldData);
            JSONObject newData = (JSONObject) CloneUtil.deepClone(originalNewData);
            //移除一些不需要比较的字段,比如创建人、创建时间等等一些不可能更改的字段
            removeNoChangeField(oldData, newData, businessType, saasMark);
            formatJson(oldData, newData);
            JSONObject handleOldData = parseJsonData(oldData, explainMap, corpid, formId, dataId, userVO, businessType, saasMark);
            JSONObject handNewData = parseJsonData(newData, explainMap, corpid, formId, dataId, userVO, businessType, saasMark);

            Map<String, Object> transferOldDataMap = JSONObject.parseObject(handleOldData.toJSONString(), new TypeReference<Map<String,Object>>(){});
            Map<String, Object> transferNewDataMap = JSONObject.parseObject(handNewData.toJSONString(), new TypeReference<Map<String,Object>>(){});
            //整理一份需要进行过滤的业务以及字段的方法;
            List<String> filterAttrs =  arrangeBusinessFilterField(businessType);
            JSONArray jsonArray = new JSONArray();
            Set<String> allAttrs = new HashSet<>();
            allAttrs.addAll(oldData.keySet());
            allAttrs.addAll(newData.keySet());
            for (String key : allAttrs) {
                FieldAttrEntity fieldAttrEntity = explainMap.get(key);
                if (Objects.isNull(fieldAttrEntity)) {
                    continue;
                }
                //这边兼容一下数据格式规范的问题
                boolean filterTag = filterNoCorrectFormat(oldData.get(key), newData.get(key), fieldAttrEntity);
                if (filterTag) {
                    continue;
                }
                //不可见的字段也需要过滤掉
                if (Objects.equals(ShowTypeEnum.NONE.getCode(), fieldAttrEntity.getShowType())) {
                    continue;
                }
                //富文本字段类型也得过滤掉,阶段推进器相关字段也得过滤掉
                if (Objects.equals(FieldTypeEnum.RICH_TEXT.getType(), fieldAttrEntity.getFieldType())
                 || Objects.equals(FieldTypeEnum.FIRST_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())
                        || Objects.equals(FieldTypeEnum.NOW_INTO_STAGE_TIME.getType(), fieldAttrEntity.getFieldType())
                || Objects.equals(FieldTypeEnum.STAGE_RATIO.getType(), fieldAttrEntity.getFieldType())) {
                    continue;
                }
                if (filterAttrs.contains(key)) {
                    continue;
                }else if (Objects.equals(FieldTypeEnum.CONTACT_NUMBER.getType(), fieldAttrEntity.getFieldType())
                        || Objects.equals(FieldTypeEnum.SWITCH_TEXT.getType(), fieldAttrEntity.getFieldType())
                        || Objects.equals(FieldTypeEnum.SELECT_PRODUCT.getType(), fieldAttrEntity.getFieldType())
                        || Objects.equals(FieldTypeEnum.SINGLE_SUB_FORM.getType(), fieldAttrEntity.getFieldType())) {
                    //不支持的子表单类型
                    continue;
                }
                try {
                    JSONObject compareResult = getCompareResult(fieldAttrEntity, oldData.get(key), newData.get(key),
                            businessType, transferOldDataMap.get(key), transferNewDataMap.get(key));
                    if (Objects.nonNull(compareResult)) {
                        jsonArray.add(compareResult);
                    }
                }catch (Exception e) {
                    log.error("error businessType:{}, key:{}, oldValue:{}, newValue:{}, transferOldValue:{}, transferNewValue:{}",
                            businessType, key, oldData.get(key), newData.get(key), transferOldDataMap.get(key), transferNewDataMap.get(key));
                }
            }
            if (Objects.nonNull(jsonArray) && jsonArray.size() > BasicConstant.ZERO) {
                WorkflowDataChangeRecordEntity workflowDataChangeRecordEntity = new WorkflowDataChangeRecordEntity(corpid, formId, saasMark, businessType,
                        changeRecordMidPojo.getWorkflowTaskId(), changeRecordMidPojo.getWorkflowNodeId(), dataId, jsonArray, userVO.getUserId(),
                        DateTimeUtil.getInt(), DateTimeUtil.getInt());
                workflowDataChangeRecordModel.insert(workflowDataChangeRecordEntity);
            }
        }
    }

    /**
     * 过滤目前知道的一些数据不规范的情况，后面再遇到继续补充
     * （1）新数据有这个字段，并且是数字类型且值为0，但是老数据都没这个字段，不认为是新增数据- 场景59490 【灰度】工作流修改记录中，不应展示未编辑的系统星级字段
     *  (2)新增加了一个关联数据字段，但是啥值都没填，这时候存的数据是0
     *
     * @param oldKeyValue
     * @param newKeyValue
     * @param fieldAttrEntity
     * @return
     */
    private boolean filterNoCorrectFormat(Object oldKeyValue, Object newKeyValue, FieldAttrEntity fieldAttrEntity) {
        if (Objects.equals(FieldTypeEnum.NUM.getType(), fieldAttrEntity.getFieldType())
            || Objects.equals(FieldTypeEnum.STAR.getType(), fieldAttrEntity.getFieldType())) {
            if (Objects.isNull(oldKeyValue) && Objects.equals(BasicConstant.ZERO, newKeyValue)) {
                return true;
            }
        }else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType())) {
            if (Objects.isNull(oldKeyValue) && Objects.equals(BasicConstant.ZERO, newKeyValue)) {
                return true;
            }
        }else if (Objects.equals(FieldTypeEnum.ADDRESS.getType(), fieldAttrEntity.getFieldType())) {
            if (Objects.isNull(oldKeyValue) && Objects.nonNull(newKeyValue)) {
                if (newKeyValue instanceof Map) {
                    Map newKeyValueMap = (Map)newKeyValue;
                    String province = (String)newKeyValueMap.get(BusinessConstant.PROVINCE);
                    String city = (String)newKeyValueMap.get(BusinessConstant.CITY);
                    String district = (String)newKeyValueMap.get(BusinessConstant.DISTRICT);
                    String address = (String)newKeyValueMap.get(BusinessConstant.ADDRESS);
                    if (StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(district)
                    && StringUtils.isEmpty(address)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 对字段进行比较，主要是比较流转表中的前后值
     *
     * @param fieldAttrEntity
     * @param oldValue
     * @param newValue
     * @param businessType
     * @param finalOldValue
     * @param finalNewValue
     * @return 返回需要插入到审批前后日志的记录信息
     */
    public JSONObject getCompareResult(FieldAttrEntity fieldAttrEntity, Object oldValue, Object newValue,
                                       Integer businessType, Object finalOldValue, Object finalNewValue) throws XbbException{
        String attr = fieldAttrEntity.getAttr();
        Integer fieldType = fieldAttrEntity.getFieldType();
        //判断是不是子表单类型
        boolean subFormTag = Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType);
        //这种情况一般就是修改的情况了,但是有可能值没有修改，这种也不记录
        if (subFormTag) {
            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
            List<? extends FieldAttrEntity> subFormAttrList = subForm.getItems();
            if (CollectionsUtil.isEmpty(subFormAttrList)) {
                return null;
            }
            //已经做过格式转化子表单需要重新封装一下
            Map<Long, Map<String, Object>> finalOldValueMap = new HashMap<>(subFormAttrList.size() * BasicConstant.TWO);
            if (Objects.nonNull(finalOldValue)) {
                JSONArray transferFinalOldValue = (JSONArray)finalOldValue;
                transferFinalOldValue.forEach(v -> {
                    Long dataId = ((JSONObject)v).getLong(BusinessConstant.SUB_DATA_ID);
                    finalOldValueMap.put(dataId, (JSONObject)v);
                });
            }

            Map<Long, Map<String, Object>> finalNewValueMap = new HashMap<>(subFormAttrList.size() * BasicConstant.TWO);
            if (Objects.nonNull(finalNewValue)) {
                JSONArray transferFinalNewValue = (JSONArray)finalNewValue;
                transferFinalNewValue.forEach(v -> {
                    Long dataId = ((JSONObject)v).getLong(BusinessConstant.SUB_DATA_ID);
                    finalNewValueMap.put(dataId, (JSONObject)v);
                });
            }
            //======================
            JSONArray oldValueJsonArray = new JSONArray();
            if (Objects.nonNull(oldValue) && oldValue instanceof List) {
                oldValueJsonArray = JSON.parseArray(JSONObject.toJSONString(oldValue));
            }else if (Objects.nonNull(oldValue)) {
                oldValueJsonArray = (JSONArray)oldValue;
            }
            List<Long> oldValueDataIdIn = new ArrayList<>();
            Map<Long, JSONObject> oldValueJsonMap = new HashMap<>();
            oldValueJsonArray.forEach(item -> {
                JSONObject oldValueJson = (JSONObject)item;
                //老的子表单是不会存在dataId为空的行记录
                Long oldValueDataId = oldValueJson.getLong(BusinessConstant.SUB_DATA_ID);
                oldValueDataIdIn.add(oldValueDataId);
                oldValueJsonMap.put(oldValueDataId, oldValueJson);
            });
            JSONArray newValueJsonArray = new JSONArray();
            if (Objects.nonNull(newValue) && newValue instanceof List) {
                newValueJsonArray = JSON.parseArray(JSONObject.toJSONString(newValue));
            }else if (Objects.nonNull(newValue)) {
                newValueJsonArray = (JSONArray)newValue;
            }
            List<Long> newValueDataIdIn = new ArrayList<>();
            Map<Long, JSONObject> newValueJsonMap = new HashMap<>();
            List<Long> newAddDataIdList = new ArrayList<>();
            newValueJsonArray.forEach(item -> {
                JSONObject newValueJson = (JSONObject)item;
                Long newValueDataId = newValueJson.getLong(BusinessConstant.SUB_DATA_ID);
                newValueDataIdIn.add(newValueDataId);
                newValueJsonMap.put(newValueDataId, newValueJson);
            });
            //封装需要新增的、删除的、修改的三个list
            List<JSONObject> shouldAddList = new ArrayList<>();
            List<Long> deepCloneOldValueDataIdIn = (List<Long>) CloneUtil.deepClone(oldValueDataIdIn);
            List<Long> deepCloneNewValueDataIdIn = (List<Long>)CloneUtil.deepClone(newValueDataIdIn);
            deepCloneNewValueDataIdIn.removeAll(deepCloneOldValueDataIdIn);
            for (Long newValueDataId : deepCloneNewValueDataIdIn) {
                shouldAddList.add(newValueJsonMap.get(newValueDataId));
            }
            //下面是需要删除的dataId
            List<JSONObject> shouldDeleteList = new ArrayList<>();
            deepCloneOldValueDataIdIn.removeAll(newValueDataIdIn);
            for (Long oldValueDataId : deepCloneOldValueDataIdIn) {
                shouldDeleteList.add(oldValueJsonMap.get(oldValueDataId));
            }
            //下面是需要修改的
            Map<Long, List<JSONObject>> shouldMap = new HashMap<>();
            oldValueDataIdIn.removeAll(deepCloneOldValueDataIdIn);
            for (Long oldValueDataId : oldValueDataIdIn) {
                JSONObject oldShouldUpdataJson = oldValueJsonMap.get(oldValueDataId);
                JSONObject newShouldUpdataJson = newValueJsonMap.get(oldValueDataId);
                List<JSONObject> finalJson = new ArrayList<>();
                finalJson.add(oldShouldUpdataJson);
                finalJson.add(newShouldUpdataJson);
                shouldMap.put(oldValueDataId, finalJson);
            }

            //下面进行数据封装
            JSONObject subFormJson = new JSONObject();
            Map<String, FieldAttrEntity> subFormMap = subFormAttrList.stream().collect(Collectors.toMap(FieldAttrEntity::getAttr, a -> a));
            List<JSONObject> content = new ArrayList<>();
            //新增数据封装
            packageSubformAddAndDeleteInfo(content, shouldAddList, OperateTypeEnum.NEW.getCode(), subFormMap, finalNewValueMap);
            //删除数据封装
            packageSubformAddAndDeleteInfo(content, shouldDeleteList, OperateTypeEnum.DELETE.getCode(), subFormMap, finalOldValueMap);
            //更新数据封装
            for (Long oldValueDataId : oldValueDataIdIn) {
                Map<String, Object> finalOldSubDataMap = finalOldValueMap.get(oldValueDataId);
                Map<String, Object> finalNewSubDataMap = finalNewValueMap.get(oldValueDataId);
                boolean shouldRecordLogTag = false;
                JSONObject rowJson = new JSONObject();
                rowJson.put(WorkflowConstant.OPERATETAG, OperateTypeEnum.EDIT.getCode());
                rowJson.put(StringConstant.DATA_ID, oldValueDataId);
                List<JSONObject> updateValueList = shouldMap.get(oldValueDataId);
                JSONObject oldUpdateValueJson = updateValueList.get(BasicConstant.ZERO);
                JSONObject newUpdateValueJson = updateValueList.get(BasicConstant.ONE);
                //如果上层oldData和newData封装的好的话，这两个json里面的key的数量应该是一致的
                Set<String> oldDataSet = Objects.isNull(oldUpdateValueJson.keySet()) ? new HashSet<>() : oldUpdateValueJson.keySet();
                Set<String> newDataSet = Objects.isNull(newUpdateValueJson.keySet()) ? new HashSet<>() : newUpdateValueJson.keySet();
                Set<String> allDataSet = Stream.concat(oldDataSet.stream(), newDataSet.stream()).collect(Collectors.toSet());
                allDataSet.remove(BusinessConstant.SUB_DATA_ID);
                for (String subItemKey : allDataSet) {
                    Object subOldValue = oldUpdateValueJson.get(subItemKey);
                    Object subNewValue = newUpdateValueJson.get(subItemKey);
                    boolean filterTag = filterNoCorrectFormat(subOldValue, subNewValue, subFormMap.get(subItemKey));
                    if (filterTag) {
                        continue;
                    }
                    if (compareOriginalValue(subOldValue, subNewValue)) {
                        shouldRecordLogTag = true;
                        FieldAttrEntity subAttrFieldAttr = subFormMap.get(subItemKey);
                        ValuePojo valuePojo = new ValuePojo(handleSpecialValue(finalOldSubDataMap.get(subItemKey), subAttrFieldAttr),
                                handleSpecialValue(finalNewSubDataMap.get(subItemKey), subAttrFieldAttr));
                        ChangeRecordSubFormColumnPojo changeRecordSubFormColumnPojo = new ChangeRecordSubFormColumnPojo(subItemKey,
                                subAttrFieldAttr.getFieldType(), valuePojo);
                        rowJson.put(subItemKey, changeRecordSubFormColumnPojo);
                    }
                }
                if (shouldRecordLogTag) {
                    content.add(rowJson);
                }
            }
            if (CollectionsUtil.isNotEmpty(content)) {
                ChangeRecordSubFormFieldBasicPojo changeRecordSubFormFieldBasicPojo = new ChangeRecordSubFormFieldBasicPojo(attr, true, content);
                return (JSONObject) JSONObject.toJSON(changeRecordSubFormFieldBasicPojo);
            }
        }else {
            //就是代表是正常字段比较 不相等返回true  相等返回false
            boolean compareResult = compareOriginalValue(oldValue, newValue);
            if (compareResult) {
                finalOldValue = handleSpecialValue(finalOldValue, fieldAttrEntity);
                finalNewValue = handleSpecialValue(finalNewValue, fieldAttrEntity);
                ValuePojo valuePojo = new ValuePojo(finalOldValue, finalNewValue);
                ChangeRecordOtherFieldBasicPojo changeRecordOtherFieldBasicPojo = new ChangeRecordOtherFieldBasicPojo(attr, fieldType,
                        subFormTag, valuePojo, OperateTypeEnum.EDIT.getCode());
                return (JSONObject) JSONObject.toJSON(changeRecordOtherFieldBasicPojo);
            }
        }
        return null;
    }

    /**
     * 比较老的值和新的值，到了这一步的对象格式其实都是一致的，荣杰上层有整理
     * 不相等返回true  相等返回false
     *
     * @param oldValue 老值
     * @param newValue 新值
     * @return
     */
    private boolean compareOriginalValue (Object oldValue, Object newValue) {
        boolean compareResult = CompareUtil.compareObjectValue(oldValue, newValue);
        return compareResult;
    }

    /**
     * 处理特殊值
     *
     * @param obj
     * @param fieldAttrEntity
     * @return
     */
    public Object handleSpecialValue(Object obj, FieldAttrEntity fieldAttrEntity) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        boolean fileTag = Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.UPLOAD.getType())
                || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.IMAGE.getType());
        if (Objects.isNull(obj) && fileTag) {
            return new JSONArray();
        }else if (Objects.isNull(obj)) {
            return "";
        }
        return obj;
    }


    /**
     * 子表单新增和删除日志信息封装类似，所以单独拆分一个方法出来
     *
     * @param content
     * @param operateTag
     * @param list
     * @param subFormMap
     * @param finalValueMap
     */
    private void packageSubformAddAndDeleteInfo(List<JSONObject> content, List<JSONObject> list, Integer operateTag, Map<String, FieldAttrEntity> subFormMap,
                                                Map<Long, Map<String, Object>> finalValueMap) {
        for (JSONObject shouldJson : list) {
            Set<String> subFormkeySet = shouldJson.keySet();
            JSONObject rowJson = new JSONObject();
            Long dataId = shouldJson.getLong(BusinessConstant.SUB_DATA_ID);
            rowJson.put(WorkflowConstant.OPERATETAG, operateTag);
            rowJson.put(StringConstant.DATA_ID, dataId);
            Map<String, Object> finalValueSubMap = finalValueMap.get(dataId);
            for (String subItemKey : subFormkeySet) {
                if (Objects.equals(BusinessConstant.SUB_DATA_ID, subItemKey)) {
                    continue;
                }
                FieldAttrEntity subAttrFieldAttr = subFormMap.get(subItemKey);
                Object subFormKeyValue = shouldJson.get(subItemKey);
                ValuePojo valuePojo = new ValuePojo(handleSpecialValue(finalValueSubMap.get(subItemKey),subAttrFieldAttr), handleSpecialValue(finalValueSubMap.get(subItemKey), subAttrFieldAttr));
                ChangeRecordSubFormColumnPojo changeRecordSubFormColumnPojo = new ChangeRecordSubFormColumnPojo(subItemKey,
                        subAttrFieldAttr.getFieldType(), valuePojo);
                rowJson.put(subItemKey, changeRecordSubFormColumnPojo);
            }
            content.add(rowJson);
        }
    }

    /**
     * 解析审批记录新老数据的方法
     *
     * @param json
     * @param explainMap
     * @param corpid
     * @param formId
     * @param dataId
     * @param userVO
     * @param businessType
     * @param saasMark
     * @return
     * @throws XbbException
     */
    public JSONObject parseJsonData(JSONObject json, Map<String, FieldAttrEntity> explainMap,
                              String corpid, Long formId, Long dataId, UserVO userVO, Integer businessType,
                              Integer saasMark) throws XbbException {
        // 通用的解析方法，主要是借用详情页的解析方法
        ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
        parseSingleRowDataDTO.setLoginUser(userVO);
        parseSingleRowDataDTO.setUserId(userVO.getUserId());
        parseSingleRowDataDTO.setCorpid(corpid);
        parseSingleRowDataDTO.setBusinessType(businessType);
        parseSingleRowDataDTO.setSaasMark(saasMark);
        parseSingleRowDataDTO.setFormId(formId);
        parseSingleRowDataDTO.setDataId(dataId);
        parseSingleRowDataDTO.setDataJsonObject(json);
        parseSingleRowDataDTO.setExplainMap(explainMap);
        List<FieldAttrEntity> explains = new ArrayList<>(explainMap.values());
        //下面是封装老数据的用户和部门信息
        Set<String> userSet = new HashSet<>();
        UserFieldUtil.getUserByDataInfo(json, explains, userSet);
        Set<Long> departmentIdSet = DepartmentFieldUtil.getDepartmentIdByDataInfo(json, explains);
        Map<String, UserEntity> userMap = new HashMap<>();
        Map<String, DepartmentEntity> departMap = new HashMap<>();
        if (CollectionsUtil.isNotEmpty(userSet)) {
            userMap = userModel.getUserEntityMap(corpid, new ArrayList<>(userSet), null);
        }
        if (CollectionsUtil.isNotEmpty(departmentIdSet)) {
            List<DepartmentEntity> departmentEntities = departmentModel.getByDepIdIn(corpid, departmentIdSet);
            departmentEntities.forEach(departmentEntity -> departMap.put(String.valueOf(departmentEntity.getId()), departmentEntity));
        }
        parseSingleRowDataDTO.setDepartmentMap(departMap);
        parseSingleRowDataDTO.setUserMap(userMap);
        parseSingleRowDataDTO.setIsProcess(true);
        ParseSingleRowDataVO parseSingleRowDataVO = formDataDetailAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
        JSONObject produceOldJson = parseSingleRowDataVO.getResult();
        for (Map.Entry<String, Object> entry : produceOldJson.entrySet()) {
            String oldKey = entry.getKey();
            Object oldKeyValue = entry.getValue();
            FieldAttrEntity fieldAttrEntity = explainMap.get(oldKey);
            if (Objects.isNull(fieldAttrEntity)) {
                continue;
            }
            Object newOldValue = transferSpecialFieldType(oldKeyValue, fieldAttrEntity, null, corpid);
            entry.setValue(newOldValue);
        }
        return produceOldJson;
    }

    /**
     * 需要针对一些fieldType再做一层转化
     *
     * @param oldKeyValue
     * @param fieldAttrEntity
     */
    public Object transferSpecialFieldType(Object oldKeyValue, FieldAttrEntity fieldAttrEntity, Map<String, Map<Long, ? extends PaasFormDataEntity>> linkDataMap, String corpid) {
        if (Objects.isNull(oldKeyValue)) {
            return "";
        }
        Integer fieldType = fieldAttrEntity.getFieldType();
        if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.LINK_BUSINESS_MULTI.getType(), fieldType)) {
            JSONArray jsonArray = (JSONArray) oldKeyValue;
            List<String> businessNameList= jsonArray.stream().map(a -> {
                String value = ((JSONObject)a).getString(StringConstant.SAAS_LINK_BUSINESS_NAME);
                return value;
            }).collect(Collectors.toList());
            String finalValue = StringUtils.join(businessNameList, ",");
            return finalValue;
        }else if (Objects.equals(FieldTypeEnum.ADDRESS.getType(), fieldType)) {
            JSONObject json = (JSONObject) oldKeyValue;
            String province = json.getString(BusinessConstant.PROVINCE);
            String city = json.getString(BusinessConstant.CITY);
            String district = json.getString(BusinessConstant.DISTRICT);
            String address = json.getString(BusinessConstant.ADDRESS);
            if (StringUtils.isEmpty(province) && StringUtils.isEmpty(city) && StringUtils.isEmpty(district) && StringUtils.isEmpty(address)) {
                return "";
            }else {
                List<String> finalValue = Arrays.asList(province, city, district, address);
                return StringUtils.join(finalValue, "");
            }
        }else if (Objects.equals(FieldTypeEnum.USER_GROUP.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.OWNERID.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.COUSERID.getType(), fieldType)) {
            if (oldKeyValue instanceof JSONArray) {
                JSONArray itemPoJoList = (JSONArray) oldKeyValue;
                List<String> finalValueList = new ArrayList<>();
                itemPoJoList.forEach(v -> {
                    finalValueList.add(((JSONObject)v).getString(BasicConstant.NAME));
                });
                return  StringUtils.join(finalValueList, ",");
            }else if (oldKeyValue instanceof List) {
                List<ReturnUserAndDepartmentPojo> resultList = (List<ReturnUserAndDepartmentPojo>)oldKeyValue;
                List<String> finalValue = resultList.stream().map(ReturnUserAndDepartmentPojo::getName).collect(Collectors.toList());
                return  StringUtils.join(finalValue, ",");
            }
        }else if (Objects.equals(FieldTypeEnum.USER.getType(), fieldType)) {
            if (oldKeyValue instanceof JSONObject) {
                return ((JSONObject)oldKeyValue).getString(BasicConstant.NAME);
            }else if (oldKeyValue instanceof ReturnUserAndDepartmentPojo) {
                ReturnUserAndDepartmentPojo result = (ReturnUserAndDepartmentPojo)oldKeyValue;
                return  result.getName();
            }
        }else if (Objects.equals(FieldTypeEnum.DEPT.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.DEPARTMENTID.getType(), fieldType)
                || FieldTypeEnum.SELECT_DEPARTMENT.getType().equals(fieldAttrEntity.getFieldType())) {
            if (oldKeyValue instanceof JSONObject) {
                return ((JSONObject)oldKeyValue).getString(BasicConstant.NAME);
            }else if (oldKeyValue instanceof ReturnUserAndDepartmentPojo) {
                ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = (ReturnUserAndDepartmentPojo)oldKeyValue;
                return returnUserAndDepartmentPojo.getName();
            }
        }else if (Objects.equals(FieldTypeEnum.DEPT_GROUP.getType(), fieldType)) {
            if (oldKeyValue instanceof JSONArray) {
                JSONArray itemPoJoList = (JSONArray) oldKeyValue;
                List<String> finalValueList = new ArrayList<>();
                itemPoJoList.forEach(v -> {
                    finalValueList.add(((JSONObject)v).getString(BasicConstant.NAME));
                });
                return  StringUtils.join(finalValueList, ",");
            }else if (oldKeyValue instanceof List) {
                List<ReturnUserAndDepartmentPojo> resultList = (List<ReturnUserAndDepartmentPojo>)oldKeyValue;
                List<String> departMents = resultList.stream().map(ReturnUserAndDepartmentPojo::getName).collect(Collectors.toList());
                return StringUtils.join(departMents, ",");
            }
        }else if (Objects.equals(FieldTypeEnum.LABEL.getType(), fieldType)) {
            if (oldKeyValue instanceof JSONArray) {
                JSONArray itemPoJoList = (JSONArray) oldKeyValue;
                List<String> finalValueList = new ArrayList<>();
                itemPoJoList.forEach(v -> {
                    finalValueList.add(((JSONObject)v).getString(BasicConstant.NAME));
                });
                return  StringUtils.join(finalValueList, ",");
            }else if (oldKeyValue instanceof List) {
                List<LabelForDetailUpadatePojo> labels = (List<LabelForDetailUpadatePojo>)oldKeyValue;
                List<String> finalValue = labels.stream().map(LabelForDetailUpadatePojo::getName).collect(Collectors.toList());
                return StringUtils.join(finalValue, ",");
            }
        }else if (Objects.equals(FieldTypeEnum.UPDATETIME.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.DATETIME.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.ENDTIME.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.CLOSETIME.getType(), fieldType)
        ) {
            //现在时间类型默认转化成yyyy-MM-dd HH:mm:ss
            String finalValue = DateTimeUtil.getStringEpochSecond(Long.parseLong(String.valueOf(oldKeyValue)), DateTimeUtil.SDF);
            return finalValue;
        }else if (Objects.equals(FieldTypeEnum.COMBO.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), fieldType)) {
            String finalValue = "";
            if (oldKeyValue instanceof  JSONObject) {
                finalValue = ((JSONObject) oldKeyValue).getString(StringConstant.TEXT);
            }else if (oldKeyValue instanceof ItemPoJo) {
                finalValue = ((ItemPoJo)oldKeyValue).getText();
            }
            return finalValue;
        }else if (Objects.equals(FieldTypeEnum.COMBO_CHECK.getType(), fieldType) || FieldTypeEnum.CHECKBOX_GROUP.getType().equals(fieldAttrEntity.getFieldType())) {
            String finalValue = "";
            if (oldKeyValue instanceof JSONArray) {
                JSONArray itemPoJoList = (JSONArray) oldKeyValue;
                List<String> finalValueList = new ArrayList<>();
                itemPoJoList.forEach(v -> {
                    finalValueList.add(((JSONObject)v).getString(StringConstant.TEXT));
                });
                finalValue = StringUtils.join(finalValueList, ",");
            }else if (oldKeyValue instanceof List) {
                List<ItemPoJo> itemPoJoList = (List<ItemPoJo>)oldKeyValue;
                List<String> finalValueList = itemPoJoList.stream().map(ItemPoJo::getText).collect(Collectors.toList());
                finalValue = StringUtils.join(finalValueList, ",");
            }
            return finalValue;
        }else if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldType)) {
            String finalValue = "";
            if (oldKeyValue instanceof  JSONObject) {
                finalValue = ((JSONObject) oldKeyValue).getString(StringConstant.TEXT);
            }else if (oldKeyValue instanceof ItemPoJo) {
                finalValue = ((ItemPoJo)oldKeyValue).getText();
            }
            return finalValue;
        }else if (FieldTypeEnum.BIRTHDAY.getType().equals(fieldAttrEntity.getFieldType())) {
            JSONObject jsonObject = (JSONObject) oldKeyValue;
            String finalValue = jsonObject.getString(StringConstant.VALUE);
            return finalValue;
        }else if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), fieldType)) {
            SubFormPoJo subForm = fieldAttrEntity.getSubForm();
            List<? extends FieldAttrEntity> items = subForm.getItems();
            Map<String, FieldAttrEntity> subItemMap = items.stream().collect(Collectors.toMap(FieldAttrEntity::getAttr, Function.identity()));
            JSONArray subItemJsonArray= JSONArray.parseArray(JSON.toJSONString(oldKeyValue));
            oldKeyValue = subItemJsonArray;
            Map<String, Map<Long, ? extends PaasFormDataEntity>> subLinkDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            //如果子表单里面有关联数据的，先批量查出来
            for (FieldAttrEntity item : items) {
                if(Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_DATA.getType())){
                    Set<Long> linkIdList = subItemJsonArray.stream().map(v -> ((JSONObject) v).getLong(item.getAttr())).collect(Collectors.toSet());
                    LinkInfoPojo linkInfo = item.getLinkInfo();
                    List<PaasFormDataEntityExt> paasFormDataEntityExtList = formDataHelp.getByDataIdList(linkIdList, linkInfo.getLinkBusinessType(), linkInfo.getLinkSaasMark(), linkInfo.getLinkFormId(), corpid);
                    Map<Long, PaasFormDataEntityExt> dataMap = paasFormDataEntityExtList.stream().collect(Collectors.toMap(PaasFormDataEntity::getId, v -> v));
                    subLinkDataMap.put(item.getAttr(), dataMap);
                }
            }

            subItemJsonArray.forEach(v -> {
                JSONObject subJson = (JSONObject)v;
                for (Map.Entry<String, Object> subEntry : subJson.entrySet()) {
                    String subKey = subEntry.getKey();
                    if (Objects.equals(BusinessConstant.SUB_DATA_ID, subKey)) {
                        continue;
                    }
                    Object subValue = subEntry.getValue();
                    FieldAttrEntity subFieldAttrEntity = subItemMap.get(subKey);
                    Object subFinalValue = transferSpecialFieldType(subValue, subFieldAttrEntity, subLinkDataMap, corpid);
                    subEntry.setValue(subFinalValue);
                }
            });
        }else if(Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType)){
            //关联数据要转换
            if(Objects.equals(oldKeyValue, Constant.ZERO)){
                return "";
            }
            if( !(oldKeyValue instanceof Long || oldKeyValue instanceof Integer) ){
                return oldKeyValue;
            }
            LinkInfoPojo linkInfo = fieldAttrEntity.getLinkInfo();
            String linkKey = linkInfo.getLinkKey();

            //关联数据是否需要查库
            boolean needSearchFlag = false;
            if(Objects.isNull(linkDataMap)){
                needSearchFlag = true;
            }else{
                Map<Long, ? extends PaasFormDataEntity> longMap = linkDataMap.get(fieldAttrEntity.getAttr());
                if(Objects.isNull(longMap) || Objects.isNull(longMap.get(Long.parseLong(oldKeyValue.toString())))){
                    needSearchFlag = true;
                }
            }

            if(needSearchFlag){
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = formDataHelp.getByDataIdList(Collections.singletonList(new Long(oldKeyValue.toString())), linkInfo.getLinkBusinessType(), linkInfo.getLinkSaasMark(), linkInfo.getLinkFormId(), corpid);
                if(CollectionsUtil.isNotEmpty(paasFormDataEntityExtList)){
                    return paasFormDataEntityExtList.get(0).getData().get(linkKey);
                }
            }else{
                return linkDataMap.get(fieldAttrEntity.getAttr()).get(Long.parseLong(oldKeyValue.toString())).getData().get(linkKey);
            }
        }else if (Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldType)) {
            if (!(oldKeyValue instanceof JSONArray || oldKeyValue instanceof  ArrayList || oldKeyValue instanceof List)) {
                return oldKeyValue;
            }
            LinkInfoPojo linkInfo = fieldAttrEntity.getLinkInfo();
            String linkKey = linkInfo.getLinkKey();
            //关联数据是否需要查库
            boolean needSearchFlag = false;
            if(Objects.isNull(linkDataMap)){
                needSearchFlag = true;
            }else{
                Map<Long, ? extends PaasFormDataEntity> longMap = linkDataMap.get(fieldAttrEntity.getAttr());
                if(Objects.isNull(longMap) || Objects.isNull(longMap.get(Long.parseLong(oldKeyValue.toString())))){
                    needSearchFlag = true;
                }
            }
            List<String> finalValue = new ArrayList<>();
            if (needSearchFlag) {
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = formDataHelp.getByDataIdList((List<Long>)oldKeyValue, linkInfo.getLinkBusinessType(), linkInfo.getLinkSaasMark(), linkInfo.getLinkFormId(), corpid);;
                paasFormDataEntityExtList.forEach(paasFormDataEntityExt -> {
                    finalValue.add(paasFormDataEntityExt.getData().getString(linkKey));
                });
                return StringUtils.join(finalValue, ",");
            }else {
                for (Long dataId : (List<Long>)oldKeyValue) {
                    Map<Long, ? extends PaasFormDataEntity> dataMap  = linkDataMap.get(fieldAttrEntity.getAttr());
                    PaasFormDataEntity paasFormDataEntity = dataMap.get(dataId);
                    finalValue.add(paasFormDataEntity.getData().getString(fieldAttrEntity.getAttr()));
                    return StringUtils.join(finalValue, ",");
                }
            }
        }
        return oldKeyValue;
    }

    /**
     * 整理一些业务需要过滤的字段
     *
     * @param businessType 业务类型
     */
    public List<String> arrangeBusinessFilterField(Integer businessType) {
        List<String> filterAttrs = new ArrayList<>();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                filterAttrs = Arrays.asList(CustomerManagementEnum.ADD_CONTACT.getAttr());
                break;
            case CONTRACT:
                filterAttrs = Arrays.asList(ContractEnum.ADD_PAYMENT_SHEET.getAttr(), ContractEnum.ADD_PAYMENT.getAttr(), ContractEnum.ADD_WRITE_OFF_PREPAYMENT.getAttr());
                break;
            case REFUND:
                filterAttrs = Arrays.asList(RefundEnum.INVOICES.getAttr(), RefundEnum.PAYMENT_SHEETS.getAttr(), RefundEnum.PAYMENTS.getAttr());
                break;
            case SUPPLIER:
                filterAttrs = Arrays.asList(SupplierEnum.ADD_SUPPLIER_CONTACT.getAttr());
                break;
            case PURCHASE:
                filterAttrs = Arrays.asList(PurchaseEnum.ADD_PAY_SHEET.getAttr(), PurchaseEnum.ADD_PAYPLAN.getAttr(), PurchaseEnum.ADD_WRITE_OFF_PREPAY.getAttr());
                break;
            case RETURNED_PURCHASE:
                filterAttrs = Arrays.asList(ReturnedPurchaseEnum.INVOICES.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getAttr());
                break;
            default:
                break;
        }
        return filterAttrs;
    }

    /**
     *
     * 移除一些不可更改的字段
     *
     * @param oldData
     * @param newData
     */
    public void removeNoChangeField(JSONObject oldData, JSONObject newData, Integer businessType, Integer saasMark) {
        oldData.remove(FieldTypeEnum.CREATORID.getAlias());
        oldData.remove(FieldTypeEnum.ADDTIME.getAlias());
        oldData.remove(FieldTypeEnum.UPDATETIME.getAlias());

        newData.remove(FieldTypeEnum.CREATORID.getAlias());
        newData.remove(FieldTypeEnum.ADDTIME.getAlias());
        newData.remove(FieldTypeEnum.UPDATETIME.getAlias());
        boolean userTeamTag = UserTeamEnum.hasTeam(businessType);
        if (userTeamTag) {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && ((oldData.get(FieldTypeEnum.OWNERID.getAlias())) instanceof String)) {
                oldData.remove(FieldTypeEnum.OWNERID.getAlias());
            }
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && ((newData.get(FieldTypeEnum.OWNERID.getAlias())) instanceof String)) {
                newData.remove(FieldTypeEnum.OWNERID.getAlias());
            }
        }
    }

    /**
     * 格式化老数据和新数据，因为两边存的格式还是有一定的差异
     * 比如团队中的数据
     *
     * @param oldData
     * @param newData
     */
    public void formatJson(JSONObject oldData, JSONObject newData){
        if (newData.containsKey(StringConstant.USER_TEAM)) {
            //主要是为了兼容阶段推进器那边过来的团队数据
            JSONArray newJsonArrayOne = newData.getJSONArray(StringConstant.USER_TEAM);
            getCorrectTeam(newData, newJsonArrayOne);
        }
        if (oldData.containsKey(StringConstant.USER_TEAM)) {
            JSONArray oldUserJsonArray = oldData.getJSONArray(StringConstant.USER_TEAM);
            JSONArray newOwnerJsonArray = newData.getJSONArray(FieldTypeEnum.OWNERID.getAlias());
            JSONArray newCouserJsonArray = newData.getJSONArray(FieldTypeEnum.COUSERID.getAlias());
            if (Objects.isNull(oldUserJsonArray)) {
                if (Objects.nonNull(newOwnerJsonArray) && newOwnerJsonArray.size() > BasicConstant.ZERO) {
                    oldData.put(FieldTypeEnum.OWNERID.getAlias(), newOwnerJsonArray);
                }
                if (Objects.nonNull(newCouserJsonArray) && newCouserJsonArray.size() > BasicConstant.ZERO) {
                    oldData.put(FieldTypeEnum.COUSERID.getAlias(), newCouserJsonArray);
                }
            }else {
                getCorrectTeam(oldData, oldUserJsonArray);
            }
        }else {
            //这边主要是为了兼容有些业务这个负责人字段作为有效字段使用，并且字段解析一定要指定list
            Object oldOwnerObj = oldData.get(FieldTypeEnum.OWNERID.getAlias());
            if (Objects.nonNull(oldOwnerObj) && (oldOwnerObj instanceof String)) {
                oldData.put(FieldTypeEnum.OWNERID.getAlias(), Arrays.asList((String)oldOwnerObj));
            }
            Object newOwnerObj = newData.get(FieldTypeEnum.OWNERID.getAlias());
            if (Objects.nonNull(newOwnerObj) && (newOwnerObj instanceof String)) {
                newData.put(FieldTypeEnum.OWNERID.getAlias(), Arrays.asList((String)newOwnerObj));
            }
        }
    }

    /**
     * 有些团队数据是以userTeam作为key的，需要转化成正确的格式
     *
     * @param data
     * @param userTeamJsonArray
     * @return
     */
    private void getCorrectTeam(JSONObject data, JSONArray userTeamJsonArray) {
        List<String> ownerList = new ArrayList<>();
        List<String> coUserList = new ArrayList<>();
        userTeamJsonArray.forEach(v -> {
            JSONObject oldUserJson = (JSONObject) v;
            Integer isMain = oldUserJson.getInteger(WorkflowConstant.ISMAIN);
            String userId = oldUserJson.getString(BasicConstant.USERID);
            if (Objects.equals(BasicConstant.ONE, isMain)) {
                ownerList.add(userId);
            }else if (Objects.equals(BasicConstant.ZERO, isMain)) {
                coUserList.add(userId);
            }
        });
        data.remove(StringConstant.USER_TEAM);
        data.put(FieldTypeEnum.OWNERID.getAlias(), ownerList);
        data.put(FieldTypeEnum.COUSERID.getAlias(), coUserList);
    }

    /**
     * 把传入的实体解析成最后需要传到记录日志中的实体
     *
     * @param workflowTransferPOJO
     */
    public ChangeRecordMidPojo getChangeRecordMidPojo(WorkflowTransferPOJO workflowTransferPOJO) {
        Data newData = workflowTransferPOJO.getData();
        JSONObject originalNewData = newData.getData();
        Long formId = newData.getFormId();
        Long dataId = newData.getId();
        Integer businessType = newData.getBusinessType();
        Integer saasMark = newData.getSaasMark();
        ChangeRecordMidPojo changeRecordMidPojo = new ChangeRecordMidPojo();
        changeRecordMidPojo.setFormId(formId);
        changeRecordMidPojo.setDataId(dataId);
        changeRecordMidPojo.setBusinessType(businessType);
        changeRecordMidPojo.setSaasMark(saasMark);
        return changeRecordMidPojo;
    }
}
